package org.loofer.ext.utils;

import org.loofer.ext.component.logger.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.InputStreamReader;
import java.util.regex.Pattern;

public final class CpuUtils {
    private static final String TAG = "CpuUtils";
    private static volatile Integer sCoreNum;
    private static volatile Long sMaxFrequency;

    private CpuUtils() {
    }

    public static int getNumCores() {
        if (sCoreNum != null) {
            return sCoreNum.intValue();
        }
        synchronized (CpuUtils.class) {
            if (sCoreNum != null) {
                int intValue = sCoreNum.intValue();
                return intValue;
            }
            Integer valueOf = Integer.valueOf(obtainNumCores());
            sCoreNum = valueOf;
            intValue = valueOf.intValue();
            return intValue;
        }
    }

    private static int obtainNumCores() {
        int coreNum = 1;
        try {
            return new File("/sys/devices/system/cpu/").listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    if (Pattern.matches("cpu[0-9]", pathname.getName())) {
                        return true;
                    }
                    return false;
                }
            }).length;
        } catch (Exception e) {
            Logger.i(TAG, "fail to obtain cpu core num", e);
            return coreNum;
        }
    }

    public static long getCpuMaxFrequency() {
        if (sMaxFrequency != null) {
            return sMaxFrequency.longValue();
        }
        synchronized (CpuUtils.class) {
            if (sMaxFrequency != null) {
                long longValue = sMaxFrequency.longValue();
                return longValue;
            }
            Long valueOf = Long.valueOf(obtainCpuMaxFrequency());
            sMaxFrequency = valueOf;
            longValue = valueOf.longValue();
            return longValue;
        }
    }

    private static long obtainCpuMaxFrequency() {
        long freq = 0;
        try {
            freq = Long.parseLong(new BufferedReader(new InputStreamReader(new ProcessBuilder(new String[]{"/system/bin/cat", "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"}).start().getInputStream())).readLine());
        } catch (Throwable e) {
            Logger.i(TAG, "fail to obtain cpu max frequency", e);
        }
        return freq;
    }
}
